<?php
namespace Api\Controller;

use Api\Event\Thirdservice\ThirdserviceEvent;
use Common\Dto\BaseDto;

/**
 * 提供给第三方使用的接口
 */
class ThirdserviceController extends PublicController {


    /**
     * 今日头条
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function toutiao()
    {
        $vService = service('video');

        // 七天内的编辑选推视频
        $map = [
            'topics'  => 3,
            'status'  => $vService::STATUS_PASS,
            'race_id' => ['$eq' => null],
            // 'create_time' => ['$gt' => (NOW_TIME - 3600*24*7)],
            'time'    => ['$gte' => 30], // 视频时间大于30秒
        ];
        $videos = $vService->where($map)->order('create_time desc')->getField('id', true);
        if ($videos) {
            $videos = $vService->where(['id' => ['$in' => $videos]])->select();
            $videos = $this->_toutiao_format($videos);
        } else {
            $videos = [];
        }

        // 比赛数据
        $map = [
            'third_tags'  => '662016006',
            'status'      => $vService::STATUS_PASS,
            'type'        => $vService::TYPE_MATCH,
        ];
        $matches = $vService->where($map)->order('create_time desc')->select();

        // 今日头条获取数据后，删除推送tag
        foreach ($matches as $value) {
            $third_tags = $value['third_tags'];
            unset($third_tags[array_search('662016006', $third_tags)]);
            $vService->save(['id' => $value['id'], 'third_tags' => array_values($third_tags)]);
        }
        $matches = $this->_toutiao_format($matches);

        $data = array_merge($videos, $matches);

        // 根据id排序
        foreach ($data as $key => &$value) {
            $ids[$key] = $value['id'];
            unset($value['id']);
        }
        array_multisort($ids, SORT_DESC, $data);
        $this->list_success($data);
    }

    private function _toutiao_format($videos) {
        $list = [];
        $gService = service('Game');
        $vService = service('Video');
        $fService = service('Favour');
        $rgEvent = event('RaceGroup');
        foreach ($videos as $key => $value) {
            if ($value['type'] == 0) {
                $game = $gService->where(['id' => $value['game_id']])->find();
                uri_format($value['thumb']);
                // uri_format($value['uri'], C('VIDEO_UPLOAD.uri_path'));

                // 默认选择720P视频
                if ($value['dpi_videos'] && $value['dpi_videos']['720'] && $value['dpi_videos']['720']['status'] == 'ok') {
                    $uri = $value['dpi_videos']['720']['uri'];
                } else {
                    $uri = $value['uri'];
                }
                uri_format($uri, C('VIDEO_UPLOAD.uri_path'));

                $link = DOMAIN . "/api/video/source/id/{$value['id']}.mp4"
                      . "?uri=" . urlencode($uri) . "&appid=662016006";
                $video = [
                    'id'              => $value['id'],
                    'title'           => "[{$game['name']}]".$value['title'],
                    'pubDate'         => date('Y-m-d H:i:s', $value['create_time']),
                    'video_cover_url' => $value['thumb'],
                    'period'          => $value['time'],
                    'play_count'      => $value['play'],
                    'tags'            => join(',', $value['tags']),
                    'link'            => $link,
                    'description'     => $value['detail'],
                    'digg'            => $value['zan'],
                    'fav'             => $fService->countByVideo($value['id']) ?: 0,
                ];
                $list[] = $video;
            } else {
                // 比赛视频  取每个短视频的信息
                if (empty($value['match_videos'])) {
                    continue;
                }
                $race  = $rgEvent->info($value['group_id']);
                $tags = join(',',
                    [
                        $race['match']['title'],
                        $race['game']['name'],
                        $race['team'][0]['name'],
                        $race['team'][1]['name'],
                    ]
                );
                $title = $race['match']['title']. ' '
                       . $race['team'][0]['name'] . ' VS '
                       . $race['team'][1]['name'] . ' ';
                foreach ($value['match_videos'] as $m) {
                    $video = $vService->where(['id' => intval($m)])->find();
                    uri_format($video['thumb']);
                    uri_format($video['uri'], C('VIDEO_UPLOAD.uri_path'));
                    $video = [
                        'id'              => intval($m),
                        'title'           => "[{$race['game']['name']}]".$title.' '.$video['title'],
                        'pubDate'         => $value['match_date'].' '.$value['match_hour'].':00',
                        'video_cover_url' => $video['thumb'],
                        'period'          => $video['time'],
                        'play_count'      => $value['play'],
                        'tags'            => $tags,
                        'link'            => $video['uri'],
                        'description'     => $video['detail'],
                    ];
                    $list[] = $video;
                }
            }
        }
        return $list;
    }

    public function query() {
        $app_id = I('app_id', 0, 'intval');
        $action = I('request.action');

        $event = ThirdserviceEvent::instance($app_id);
        if (empty($event)) {
            $this->error(self::$API_ERROR['SERVER'], '参数错误');
        }

        $request = I('');
        unset($request['app_id']);
        unset($request['action']);
        $dto = new BaseDto($request);

        $result = $event->get($action, $dto);

        if ($result === false) {
            $this->error(self::$API_ERROR['SERVER'], '参数错误');
        }
        $this->success('请求成功', $result);
    }

    public function post() {
        $uid = $this->getUid(I('appToken', '', 'trim'));
        if (!$uid) {
            $this->error(self::$API_ERROR['SERVER'], '参数错误');
        }

        $app_id = I('app_id', 0, 'intval');
        $action = I('request.action');

        $event = ThirdserviceEvent::instance($app_id);
        if (empty($event)) {
            $this->error(self::$API_ERROR['SERVER'], '参数错误');
        }

        $request = I('');
        unset($request['app_id']);
        unset($request['action']);
        $dto = new BaseDto($request);
        $dto->uid = $uid;

        $result = $event->get($action, $dto);

        if ($result === false) {
            $this->error(self::$API_ERROR['SERVER'], '参数错误');
        }
        $this->success('请求成功', $result);
    }
}